package com.work.account2.service;

import com.work.account2.entity.Account;
import com.work.account2.repository.AccountDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * Description：
 *
 * @author fangliangsheng
 * @date 2019-04-05
 */
@Service
public class AccountService {

    private static final String ERROR_USER_ID = "1002";
    @Resource
    private AccountDAO accountDAO;

    @Resource
    private TccAccountService tccAccountService;

    @Transactional(rollbackFor = Exception.class)
    public void reduce(String userId, BigDecimal money) {
        Account account = accountDAO.findByUserId(userId);
        account.setMoney(account.getMoney().subtract(money));
        accountDAO.updateById(account);

        //模拟异常 1002
        if (ERROR_USER_ID.equals(userId) && money.compareTo(BigDecimal.ZERO)>0) {
            throw new RuntimeException("account branch exception");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void tccReduce(String userId, BigDecimal orderMoney) {
        tccAccountService.prepare(null, userId, orderMoney);
    }
}
